import sqlite3, datetime, json
from django.shortcuts import render
from django.http import HttpResponse
from shared_resources import *

def class_view(request, class_id):
	initialize(request)
	output = ""

	if not request.session["rights"]["edit_classes"]:
		output += '<p class="bg-warning">'+t('You do not have the rights to edit classes.')+'</p>'
	else:
		sql_connection = sqlite3.connect(global_vars["database"])
		sql_cursor = sql_connection.cursor()    

		students_classes = {}
		db_rows = sql_cursor.execute("""SELECT id, student_id, (select first_name from students where id = student_id), (select middle_name from students where id = student_id), (select last_name from students where id = student_id), start_time, end_time FROM student_classes where class_id = ?""", (class_id,))
		for id, student_id, first_name, middle_name, last_name, start_time, end_time in db_rows:
			id = int(id)
			name = display_name(first_name, middle_name, last_name)
			students_classes[id] = {"id": id, "student_id": student_id, "name": name, "start_time": int(start_time), "end_time": int(end_time), "credit": 0}
		
		for id in students_classes:
			db_rows = sql_cursor.execute("""select credit from student_credit where student_class_id = ?""", (id,))
			for row in db_rows:
				students_classes[id]["credit"] += row[0]
		
		db_rows = sql_cursor.execute("""select id, start_time, end_time from lessons where class_id = ?""", (class_id, ))
		for lesson_id, start_time, end_time in db_rows:
			for id in students_classes:
				if start_time > students_classes[id]["start_time"] and (end_time < students_classes[id]["end_time"] or students_classes[id]["end_time"] == -1):
					students_classes[id]["credit"] -= end_time - start_time

		output += '<table class="table viewuser table-striped table-hover"><tr><th style="text-align: left;">'+t('Student')+'</th><th>'+t('Credit left')+'</th></tr>'
		for id in students_classes:
			output += '<tr><td><a href="/office/student-view/'+str(students_classes[id]["student_id"])+'/">'+students_classes[id]["name"]+'</td><td><p style="color: '+('green' if students_classes[id]["credit"] >= 0 else 'red')+';">'+str(students_classes[id]["credit"]/float(60*60))+"</p></td></tr>"
		output += '</table>'	

	return format_response(version["icons"]["classes"]+t("Class Overview"), output)

def class_edit(request, class_id):
	initialize(request)
	output = ""

	if not request.session["rights"]["edit_classes"]:
		output += '<p class="error_message">'+t('You do not have the rights to edit classes.')+'</p>'
	else:
	
		def timestamp_to_date(timestamp):
			if int(timestamp) == -1:
				return "-1"
			date = datetime.datetime.fromtimestamp(timestamp)
			return date.strftime('%d-%m-%Y')
			
		def date_to_timestamp(date):
			if to_int(date) == -1:
				return -1
			return int(time.mktime(datetime.datetime.strptime(date, "%d-%m-%Y").timetuple()))
		
		sql_connection = sqlite3.connect(global_vars["database"])
		sql_cursor = sql_connection.cursor()    

		result = sql_cursor.execute("""select subject, description, (select first_name from staff where id = teacher_id), teacher_id, edit_mode from classes where id = ?""", (class_id,)).fetchone()
		
		if result == None:
			output += '<div class="col-xs-12"><p class="bg-warning">'+t('Class does not exist')+'</p></div>'
		else:
			if not (request.session["user"]["administrator"] or request.session["user"]["organizer"] or request.session["user"]["id"] == result[3]):
				output += t('You do not have rights to view this page.')

			if 'class_subject' in request.POST.keys():
				students = json.loads(request.POST['students'])
				i = 0
				values = (to_int(request.POST["class_subject"]), request.POST["class_description"], int(request.POST.get("edit_mode", 0)), to_int(class_id))
				sql_cursor.execute("""update classes set subject = ?, description = ?, edit_mode = ? where id = ?""", values)
				sql_cursor.execute("""delete from student_classes where class_id = ?""", (class_id, ))
				for student in students:
					start_time = date_to_timestamp(students[student]["start_time"])
					end_time = date_to_timestamp(students[student]["end_time"])
					end_time = -1 if end_time == -1 else max(start_time, end_time)
					if int(students[student]["student_class_id"]) == -1:
						values = (to_int(student), to_int(class_id), start_time, end_time)
						sql_cursor.execute("""INSERT INTO student_classes ('student_id', 'class_id', 'start_time', 'end_time') VALUES (?, ?, ?, ?)""", values)
					else:
						values = (int(students[student]["student_class_id"]), to_int(student), to_int(class_id), start_time, end_time)
						sql_cursor.execute("""INSERT INTO student_classes ('id', 'student_id', 'class_id', 'start_time', 'end_time') VALUES (?, ?, ?, ?, ?)""", values)
				sql_connection.commit()
				
				# get updated details
				result = sql_cursor.execute("""select subject, description, (select first_name from staff where id = teacher_id), teacher_id, edit_mode from classes where id = ?""", (class_id,)).fetchone()
			
			output += (
			'<form action="?" method="post">'
			'<table class="table newuser">'
			'<tr><td>'+t('Teacher')+'</td><td>'+result[2]+'</td></tr>'
			'<tr><td>'+t('Subject')+'</td>'
			'<td><select name="class_subject">')
			for key, type in enumerate(class_subjects+["Other"]):
				key = -1 if type == "Other" else key
				output += '<option value="'+str(key)+'"'+(" selected" if result[0] == key else "")+'>'+type+'</option>'
			output += ('</select></td></tr>'
			'<tr><td>'+t('Description')+'</td><td><div class="textareawrapper"><textarea name="class_description" rows="4" cols="50">'+result[1]+'</textarea></div></td></tr>'
			'<br />'
			'<tr><td>'+t('Select students')+'</td>'
			'<td><div class="ui-widget">'
			'<input id="student_autocomplete">'
			'</div></td></tr>'
			'<tr><td>'+t('Teacher/students can cancel lessons')+'</td><td><input name="edit_mode" type="checkbox" value="1" '+("" if int(result[4]) == 0 else "checked")+'></td></tr>'
			'<tr><td>'+t('Students')+'</td>'
			'<td><div id="selected_students">'
			'</div></td></tr>'
			'<tr><td>'+t('Periodic students')+'</td>'
			'<td><div id="previous_students">'
			'</div></td></tr>'
			'<input type="hidden" name="students" id="students" value="[]">'
			'<tr><td></td><td><input class="btn btn-primary" type="submit" value="'+t('Update')+'"></td></tr>'
			'</table>'
			'</form>'
			'<script>'
			'var current_date = "'+timestamp_to_date(int(time.time()))+'";'
			'var student_list = [ ')
			
			db_rows = sql_cursor.execute("""SELECT id, first_name, middle_name, last_name FROM students where active = 1""")
			for row in db_rows:
				output += '{label: "'+display_name(row[1],row[2],row[3])+'", value: {student_class_id: -1, name: "'+display_name(row[1],row[2],row[3])+'", id: "'+str(row[0])+'", start_time: -1, end_time: -1}}, '
			
			output += """
			];
			
			var selected_students = {};

			$(function() {
				$( "#student_autocomplete" ).autocomplete({
					source: student_list,
					select: function( event, ui ) {
						add_student(ui.item.value);
						return false;
						}
				});
			});
			
			function add_student(val){
				student_list = _.without(student_list, _.findWhere(student_list, {label: val.name}));
				selected_students[val.id] = val;
				$( "#student_autocomplete" ).autocomplete( "option", "source", student_list);
				$( "#student_autocomplete" ).val("");
				list_selected_students();
			}
			
			function current_student(id){
				selected_students[id]["start_time"] = -1;
				selected_students[id]["end_time"] = -1;
				list_selected_students();			
			}
			
			function remove_student(id){
				selected_students[id]["start_time"] = "01-01-2016";
				selected_students[id]["end_time"] = current_date;
				list_selected_students();
			}
			
			function delete_student(id){
				var retVal = confirm('"""+t("WARNING: Deleting this student will affect the calculation of his/her credit. If the student has had any classes, please move him/her to previous students instead.")+"""');
				if( retVal == true ){
					student_list.push({ label: selected_students[id]["name"], value: selected_students[id] });
					delete selected_students[id];
					$( "#student_autocomplete" ).autocomplete( "option", "source", student_list);
					list_selected_students();
				}
			}
			
			function change_value(from_to, id){
				if (from_to == 0){
					selected_students[id]["start_time"] = $("#"+id+"_from_date").val();
				}else{
					selected_students[id]["end_time"] = $("#"+id+"_to_date").val();
				}
				$( "#students" ).val(JSON.stringify(selected_students));
			}
			
			function list_selected_students(){
				var selected_string = '"""+t('None')+"""';
				var previous_string = '"""+t('None')+"""';
				
				for(id in selected_students){
					if(selected_students[id]["end_time"] == -1){
						if(selected_string == '"""+t('None')+"""'){
							selected_string = '<table><tr><td style="width: 110px;">"""+t("Name")+"""</td><td style="width: 110px;"></td><td style="width: 110px;"></td><td></td>';
						}
						selected_string += '<tr><td><a href="/office/student-edit/'+id+'/">'+selected_students[id]["name"]+'</a></td><td></td><td></td><td><a href="javascript:void(0);" onclick="remove_student('+id+');">"""+version["icons"]["down"]+"""</a> <a href="javascript:void(0);" onclick="delete_student('+id+');">"""+version["icons"]["delete"]+"""</a></td></tr>';
					}else{
						if(previous_string == '"""+t('None')+"""'){
							previous_string = '<table><tr><td style="width: 110px;">Name</td><td style="width: 110px;">From</td><td style="width: 110px;">To</td><td></td>';
						}
						previous_string += '<tr><td><a href="/office/student-edit/'+id+'/">'+selected_students[id]["name"]+'</a></td><td><input onchange="change_value(0, '+id+')" class="date" id="'+id+'_from_date" value="'+selected_students[id]["start_time"]+'" style="width: 100px;"></td><td><input onchange="change_value(1, '+id+')" class="date" id="'+id+'_to_date" value="'+selected_students[id]["end_time"]+'" style="width: 100px;"></td><td><a href="javascript:void(0);" onclick="current_student('+id+');">"""+version["icons"]["up"]+"""</a> <a href="javascript:void(0);" onclick="delete_student('+id+');">"""+version["icons"]["delete"]+"""</a></td></tr>';
					}
				}
				selected_string += "</table>";
				previous_string += "</table>";
				$( "#selected_students" ).html(selected_string);
				$( "#previous_students" ).html(previous_string);
				$(function() {
					$( ".date" ).datepicker({
						dateFormat: "dd-mm-yy",
						firstDay: 1,
					});
				});
				$( "#students" ).val(JSON.stringify(selected_students));
				console.log($( "#students" ).val());
			}
			
			$( document ).ready(function() {"""
			db_rows = sql_cursor.execute("""select id, student_id, (select first_name from students where id = student_classes.student_id), (select middle_name from students where id = student_classes.student_id), (select last_name from students where id = student_classes.student_id), start_time, end_time from student_classes where class_id = ?""", (class_id,))

			for student_class_id, student_id, first_name, middle_name, last_name, start_time, end_time in db_rows:
				output += 'add_student({student_class_id: "'+str(student_class_id)+'", name: "'+display_name(first_name, middle_name, last_name)+'", id: "'+str(student_id)+'", start_time: "'+timestamp_to_date(start_time)+'", end_time: "'+timestamp_to_date(end_time)+'"});\n'
			output += """
			});
			</script>
			"""	
			
	return format_response(version["icons"]["classes"]+t("Edit Class"), output)

def class_overview(request):
	initialize(request)
	output = ""

	if not request.session["rights"]["view_classes"]:
		output += '<p class="bg-warning">'+t('You do not have the rights to view classes.')+'</p>'
	else:
		sql_connection = sqlite3.connect(global_vars["database"])
		sql_cursor = sql_connection.cursor()    
		
		if 'class_subject' in request.POST.keys():
			students = json.loads(request.POST['students'])
			i = 0
			if len(students) > 0:
				values = (to_int(request.POST["class_teacher"]), to_int(request.POST["class_subject"]), request.POST["class_description"], int(request.POST.get("edit_mode", 0)))
				sql_cursor.execute("""INSERT INTO classes ('teacher_id', 'subject', 'description', 'edit_mode') VALUES (?, ?, ?, ?)""", values)
				class_id = sql_cursor.lastrowid
				for student in students:
					values = (to_int(student), to_int(class_id), -1, -1)
					sql_cursor.execute("""INSERT INTO student_classes ('student_id', 'class_id', 'start_time', 'end_time') VALUES (?, ?, ?, ?)""", values)
				sql_connection.commit()
				output += '<p class="bg-success">'+t('Class created')+'</p>'

		if 'active' in request.POST.keys():
			sql_cursor.execute("""update classes set active = ? where id = ?""", (request.POST["active"], request.POST["id"]))
			sql_connection.commit()

		if 'delete' in request.POST.keys():
			if not request.session["rights"]["delete_classes"]:
				output += '<p class="error_message">'+t('You do not have the rights to delete classes.')+'</p>'
			else:
				result = sql_cursor.execute("""select (select first_name from staff where id = teacher_id), subject, description from classes where id = ?""", (request.POST["delete"],)).fetchone()
				if result != None:
					log_message(sql_cursor, t("Class deleted (Teacher: %s, Subject: %s, Desctription: %s)", (to_str(result[0]), class_subjects[result[1]], result[2])))
					
					lessons = []
					db_rows = sql_cursor.execute("""select id from lessons where class_id = ?""", (request.POST["delete"],))
					for row in db_rows:
						lessons.append(row[0])
					for lesson in lessons:
						sql_cursor.execute("""delete from student_feedback where lesson_id = ?""", (lesson,))
						sql_cursor.execute("""delete from teacher_feedback where lesson_id = ?""", (lesson,))
					sql_cursor.execute("""delete from student_classes where class_id = ?""", (request.POST["delete"],))
					sql_cursor.execute("""delete from lessons where class_id = ?""", (request.POST["delete"],))
					sql_cursor.execute("""delete from classes where id = ?""", (request.POST["delete"],))
					sql_connection.commit()
					output += '<p class="bg-success">'+t('Class deleted')+'</p>'

		if request.session['show_disabled']:
			db_rows = sql_cursor.execute("""SELECT id, subject, description, (select count(student_id) from student_classes where class_id = classes.id), (select first_name from staff where id = classes.teacher_id), (select middle_name from staff where id = classes.teacher_id), (select last_name from staff where id = classes.teacher_id), teacher_id, active FROM classes order by active desc, teacher_id""")
		else:
			db_rows = sql_cursor.execute("""SELECT id, subject, description, (select count(student_id) from student_classes where class_id = classes.id), (select first_name from staff where id = classes.teacher_id), (select middle_name from staff where id = classes.teacher_id), (select last_name from staff where id = classes.teacher_id), teacher_id, active FROM classes where active = 1 order by teacher_id""")
		
		output += '<div class="row"><div class="col-xs-12 col-md-6"><h3>'+t('Current Classes')+'</h3><table class="table viewuser table-striped table-hover"><tr><th>'+t('Teacher')+'</th><th>'+t('Subject')+'</th><th>'+t('Students')+'</th><th>'+t('Description')+'</th><th style="text-align: right;"></th></tr>'
		
		for id, subject, description, student_count, first_name, middle_name, last_name, teacher_id, active in db_rows:
			name = display_name(first_name, middle_name, last_name)
			output += '<tr'+('' if active else ' class="disabled_row"')+'><td><a href="/office/staff-info/'+str(teacher_id)+'/">'+name+'</td><td style="text-align:right">'+(t("Other", (), True) if subject == -1 else class_subjects[subject])+'</td><td>'+str(student_count)+'</td><td>'+description+'</td><td>'
			if request.session["rights"]["edit_classes"]:
				output += '<a href="/office/class-view/'+str(id)+'/">'+version["icons"]["info"]+'</a>'
				output += '<a href="/office/class-edit/'+str(id)+'/">'+version["icons"]["edit"]+'</a>'
			output += '<a href="/office/class-schedule/'+str(id)+'/">'+version["icons"]["schedule2"]+'</a>'
			if request.session["rights"]["edit_classes"]:
				output += '<a href="#" onclick="post_request({\'active\': '+str(1 - active)+', \'id\': '+str(id)+'});">'+(version["icons"]["enable"] if int(active) == 0 else version["icons"]["disable"])+'</a>'
				output += '<a href="#" onclick="confirm_delete(\''+str(id)+'\', \''+name+'s '+class_subjects[subject]+'\')">'+version["icons"]["delete"]+'</a>'
			output += '</td></tr>'
		
		output += ('</table><button class="btn btn-primary" style="display: inline; margin-top: 10px; float: right;" type="submit" onclick="post_request({\'show_disabled\': '+str(1 - int(request.session['show_disabled']))+'});">'+(t('Hide disabled', (), True) if request.session['show_disabled'] else t('Show disabled', (), True))+'</button></div>'
		'<div class="col-xs-12 col-md-6"><h3>'+t('Create New Class')+'</h3>'
		'<form action="?" method="post">'
		'<table class="newuser table">'
		'<tr><td>'+t('Teacher')+'</td>'
		'<td><select name="class_teacher">')
		db_rows = sql_cursor.execute("""SELECT id, first_name, middle_name, last_name FROM staff""")
		for row in db_rows:
			output += '<option value="'+str(row[0])+'">'+display_name(row[1],row[2],row[3])+'</option>'
		output += ('</select></td></tr>'
		'<tr><td>'+t('Subject')+'</td>'
		'<td><select name="class_subject">')
		for key, _type in enumerate(class_subjects+["Other"]):
			key = -1 if _type == t("Other", (), True) else key
			output += '<option value="'+str(key)+'">'+_type+'</option>'
		output += ('</select></td></tr>'
		'<tr><td>'+t('Description')+'</td><td><div class="textareawrapper"><textarea name="class_description" rows="4" cols="50"></textarea></div></td></tr>'
		'<tr><td>'+t('Teacher/students can cancel lessons')+'</td><td><input name="edit_mode" type="checkbox" value="1"></td></tr>'
		'<script>'
		'var student_list = [ ')
		
		db_rows = sql_cursor.execute("""SELECT id, first_name, middle_name, last_name FROM students where active = 1""")
		for row in db_rows:
			output += '{ label: "'+display_name(row[1],row[2],row[3])+'", value: "'+str(row[0])+'" }, '
		
		output += """
		];
		
		var selected_students = {}

	  $(function() {
		$( "#student_autocomplete" ).autocomplete({
				source: student_list,
				select: function( event, ui ) {
					add_student(ui.item.value, ui.item.label);
					return false;
					}
			});
		});
		
		function add_student(id, name){
			student_list = _.without(student_list, _.findWhere(student_list, {value: id}));
			selected_students[id] = name;
			$( "#student_autocomplete" ).autocomplete( "option", "source", student_list);
			$( "#student_autocomplete" ).val("");
			list_selected_students();
		}
		
		function remove_student(id, name){
			student_list.push({ label: name, value: ''+id });
			delete selected_students[id];
			$( "#student_autocomplete" ).autocomplete( "option", "source", student_list);
			list_selected_students();
		}
		
		function list_selected_students(){
			console.log(selected_students);
			var string = "";
			var ids = [];
			for(id in selected_students){
				string += selected_students[id]+' <a href="javascript:void(0);" onclick="remove_student('+id+', \\''+selected_students[id]+'\\');">"""+version["icons"]["delete"]+"""</a><br />';
				ids.push(id); 
			}
			$( "#selected_students" ).html(string);
			$( "#students" ).val(JSON.stringify(ids));
		}
		
		function confirm_delete(id, name){
			var retVal = confirm('"""+t('Are you sure you want to remove %%s class? Any lessons connected with this class will be cancelled.')+"""'.replace('%s', '"""+name+"""'));
			if( retVal == true ){
				post_request({"delete": id}, "/office/class-overview/");
				return true;
			}
		}
		</script>
	  
		<tr><td>"""+t('Select students')+"""</td>
		<td><div class="ui-widget">
		<input id="student_autocomplete">
		</div></td></tr>
		<tr><td>"""+t("Students in the class")+"""</td>
		<td><div id="selected_students">
		</div>
		</td></tr>
		<input type="hidden" name="students" id="students" value="[]">
		<tr><td></td><td><input class="btn btn-primary" type="submit" value='"""+t('Create')+"""'></td></tr>
		</table></form>
		</div></div>
		"""

	return format_response(version["icons"]["classes"]+t("Classes"), output)
	
def class_schedule(request, class_id, selected_week):	
	initialize(request)
	output = ""

	sql_connection = sqlite3.connect(global_vars["database"])
	sql_cursor = sql_connection.cursor()    

	if not request.session["rights"]["view_classes"]:
		output += '<p class="bg-warning">'+t('You do not have the rights to view classes.')+'</p>'
	else:
		request.session['schedule_week'] = int(selected_week) if selected_week != None else request.session['schedule_week']
		
		schedule = {0:{},1:{},2:{}}
		
		# Lesson schedule
		result = sql_cursor.execute("""select subject, description from classes where id = ?""", (class_id,)).fetchone()
		classes = {class_id: {"description": class_subjects[result[0]]+" - "+result[1]}}
		
		lessons = {}
		db_rows = sql_cursor.execute("""select start_time, end_time, (select teacher_id from classes where id = lessons.class_id), id, lessons.room_id, (select subject from classes where id = lessons.class_id), (select first_name from staff where id = (select teacher_id from classes where id = lessons.class_id)), class_id, confirmed from lessons where class_id = ? and start_time >= ? and end_time <= ?""", (class_id, week_to_stamp(request.session['schedule_week']), week_to_stamp(request.session['schedule_week']+1)))
		for row in db_rows:
			schedule[2][row[3]] = {"id": row[3], "start_time": row[0] - week_to_stamp(request.session['schedule_week']), "end_time": row[1] - week_to_stamp(request.session['schedule_week']), "type": (3 if row[8] == 1 else 4), "editable": 1, "layer": -1}
			lessons[row[3]] = {"id":row[3], "room_id":row[4], "subject_id":row[5], "teacher_name":row[6], "class_id":row[7], "can_confirm": False}
		
		student_names = []
		db_rows = sql_cursor.execute("""select (select first_name from students where id = student_id) from student_classes where class_id = ?""", (class_id,))
		for row in db_rows:
			student_names.append(row[0])
		classes[class_id]["students"] = ', '.join(student_names[:2]) + ("..." if len(student_names) > 2 else "")
		
		rooms = {}
		db_rows = sql_cursor.execute("""SELECT id, name FROM classrooms""")
		for row in db_rows:
			rooms[row[0]] = {"name": row[1], "unavailable": {}}
		
		output += schedule_html(0, schedule, "/office/class-schedule/"+class_id, lessons, rooms, classes)
 
	return format_response(version["icons"]["classes"]+t("Class schedule"), output)
